<template>
  <div>
    <div
      style="padding-top: 30px"
      v-if="showSearch"
      :class="{
        'enter-level flipInX': showSearch,
      }"
    >
      <el-form :inline="true" :model="syslogininfor" class="demo-form-inline">
        <el-form-item label="登录地址">
          <el-input
            v-model="syslogininfor.ipaddr"
            placeholder="请输入登录地址"
            clearable
          />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input
            v-model="syslogininfor.userName"
            placeholder="请输入用户名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="syslogininfor.status" placeholder="类型" clearable>
            <el-option label="成功" value="0" />
            <el-option label="失败" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="访问时间">
          <div class="block">
            <el-date-picker
              v-model="loginTime"
              placeholder="-"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="getLogDataList" :icon="Search">
            搜索
          </el-button>
          <el-button type="info" @click="reset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 30px">
      <div
        style="
          padding-bottom: 20px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>
          <el-button
            :icon="Delete"
            type="danger"
            plain
            @click="removeLog"
            :disabled="isBatch"
            >删除</el-button
          >
          <el-button :icon="Scissor"  type="danger" plain @click="clearData">
            清空</el-button>
          <el-button :icon="Bottom"  type="warning" plain @click="open(null,2)">
            导出</el-button>
        </div>
        <div>
          <el-button
            :icon="Search"
            circle
            @click="showSearch = !showSearch"
          ></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        style="width: 100%"
        height="600"
        row-key="id"
        :tree-props="{ children: 'list', checkStrictly: true }"
        @selection-change="handleSelectionChange"
        v-loading="dataLoding"
        
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column
          property="infoId"
          label="访问编号"
          width="105"
        />
        <el-table-column property="userName" label="用户名称" />
        <el-table-column property="ipaddr" label="登录地址" />
        <el-table-column property="loginLocation" label="登录地址" />
        <el-table-column label="消息" width="180">
        <template #default="scope">
          <el-popover effect="light" trigger="hover" placement="top" width="auto">
            <template #default>
              <div>{{ scope.row.msg }}</div>
            </template>
            <template #reference>
              <el-tag>{{ scope.row.userName }}</el-tag>
            </template>
          </el-popover>
        </template>
      </el-table-column>
        <el-table-column property="os" label="操作系统" />
        <el-table-column #default="scope" label="登录状态" width="200">
          <template  v-if="scope.row.status==0"> <el-tag type="success">登录成功</el-tag></template>
          <template  v-if="scope.row.status==1"><el-tag type="danger">登录失败</el-tag></template>
        </el-table-column>
        <el-table-column label="访问时间" width="200">
          <template #default="scope">{{tool.formatDateToYYYYMMDD(scope.row.loginTime)}}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button @click="open(scope.row,1)" type="text" :icon="Bottom">
              导出
            </el-button>

            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定要删除该日志吗？"
              @confirm="oneremoveLog(scope.row)"
              @cancel="removeCnacle"
            >
              <template #reference>
                <el-button type="text" :icon="Delete"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-pagination
          :hide-on-single-page="false"
          background
          layout="prev, pager, next"
          :total="pages.total"
          :page-size="syslogininfor.pageSize"
          :page-count="pages.pages"
          @current-change="changePage"
          :pager-count="15"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import request from "@/assets/js/request";
import { ref, onMounted, reactive } from "vue";
import { ElMessage,ElMessageBox  } from "element-plus";
import tool from '@/assets/js/tool'
import {
  Search,
  Refresh,
  Delete,
  Scissor,
  Bottom
} from "@element-plus/icons-vue";

let syslogininfor=reactive({
  ipaddr:'',
  userName:'',
  status:null,
  beginTime:null,
  endTime:null,
  idlist:'',
  pageNum:1,
  pageSize:20
})
const loginTime=ref()
const dataList=ref([])
const pages=ref({
  total:0,
  pages:0
})

const showSearch = ref(true);
const dataLoding = ref(false);

// 记录当前批量删除tag的步骤
const selectable = ref();
const isBatch = ref(true);
const selectKey = ref([]);
//导出提示语
const msg=ref('确定导出所有日志数据？数据过大时可能较慢！')

//导出请求
const fetchFile=()=>{
    separate(loginTime.value);
    request.post(`/login_infor/exce`,syslogininfor,{responseType:'arraybuffer'}).then((response) => {
            const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = '登录日志.xlsx';// 设置下载文件名
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
    })
    .catch(err =>{
      ElMessage.error(err.message);
       }
    )
}
//导出事件
const open = (data,key) => {
  if(key===2){
    getIdList(selectKey.value);}
  else{
    msg.value='确定导出该日志消息？'
    getId(data)}
  ElMessageBox.confirm(
    msg.value,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      fetchFile();
    }).catch(() => {
      msg.value='确定导出所有数据？'
      syslogininfor.idlist='';
      ElMessage({
        type: 'success',
        message: 'Canceled',
      })
    })
}
//确定开始和结束时间分开
const separate=(data)=>{
  if(data)
  {  
    syslogininfor.beginTime=data[0];
    syslogininfor.endTime=data[1]; 
  }
}
//确定idlist
const getIdList=(data)=>{
  if(data.length>0){
    msg.value='确定导出所选日志消息？'
    data.forEach(element => {
      syslogininfor.idlist=element+','+syslogininfor.idlist;
    });
  }
}
//单个idlist确定
const getId=(data)=>{
    syslogininfor.idlist=data.infoId;    
}
//获取数据
const getLogDataList=()=>{
  dataLoding.value = true;
  separate(loginTime.value);
  getIdList(selectKey.value);
  request.post('/login_infor/page',syslogininfor).then((res) => {
          if(res.code===200){
            dataList.value=res.data.list;
            pages.value.total=res.data.total;
            pages.value.pages=res.data.pages;
          }else {
        ElMessage.error(res.msg);
      }
      dataLoding.value = false;
  })
  .catch(err =>{
    ElMessage.error(err.message);
     }
  )
  setTimeout(() => {
    dataLoding.value = false;
  }, 5000);
}
//换页
const changePage = (pageIndex) => {
  syslogininfor.pageNum = pageIndex;
  getLogDataList();
};
//删除请求
const removeRequest=()=>{
  request.post(`/login_infor/remove?idlist=`+syslogininfor.idlist).then((res) => {
    if(res.code===200){
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    }else{
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    }
  }).catch(err =>{
    ElMessage.error(err.message);
     }
  )
}
//批量删除事件
const removeLog=()=>{
  getIdList(selectKey.value)
  ElMessageBox.confirm(
    '确定删除所选项?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
      removeRequest();
      getLogDataList();
    }).catch(() => {
      selectKey.value=[]
      syslogininfor.idlist=''
    })
    
}
//单删确定
const oneremoveLog=(data)=>{
  syslogininfor.idlist=data.infoId;
  removeRequest();
  getLogDataList();
}
//单删取消
const removeCnacle=()=>{
  syslogininfor.idlist='';
}
//清空
const clearData=()=>{
  ElMessageBox.confirm(
    '确认要清空所有数据?危险！不可逆！',
    'error',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
      request.post('/login_infor/clear').then((res) => {
        if(res.code===200){
          ElMessage({
            type: 'success',
            message: '数据已全部清空',
          })
          getLogDataList();
        }else{
          ElMessage.error(res.msg)
        }
      }).catch(err =>{ElMessage.error(err.message);}
      )
    }).catch(() => {}
  )
}
const reset = () => {
  loginTime.value=null;
  syslogininfor={
    ipaddr:'',
    userName:'',
    status:null,
    beginTime:null,
    endTime:null,
    idlist:'',
    pageNum:1,
    pageSize:20
  }
  getLogDataList(); 
};

// 多选
const handleSelectionChange = (val) => {
  console.log(val);
  let arr = val.map((item) => item.infoId);
  selectKey.value = arr;
  if (selectKey.value.length > 0) {
    isBatch.value = false;
  } else {
    isBatch.value = true;
  }
};

onMounted(() => {
  getLogDataList();
});
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-form {
  display: inline;
}

.activeTag {
  background: #fef0f0;
  border: #fde2e2 1px solid;
  color: #f67777;
}
</style>



